package de.kuttenmann.jflake;
import java.util.Collections;
import java.util.List;

public class Node
{
	private final Sphere bound;
	private final Sphere leaf;
	private final List<Node> subNodes;

	public Node(Sphere bound, Sphere leaf, List<Node> subNodes)
	{
		this.bound = bound;
		this.leaf = leaf;
		this.subNodes = Collections.unmodifiableList(subNodes);
	}

	public Hit intersect(final Ray ray, final Hit closest, boolean shadow)
	{
		Hit hit = closest;
		if (this.bound.intersect(ray) < closest.getDistance())
		{
			double distance = this.leaf.intersect(ray);
			if(distance < closest.getDistance())
			{
				if (shadow) /*if hit, break for shadows*/
				{
					hit = new Hit(distance);
				}
				else
				{
					hit = this.leaf.calculateHit(ray, distance);
				}
			}

			for (Node currentSubNode : this.subNodes)
			{
				hit = currentSubNode.intersect(ray, hit, shadow);
			}
		}
		return hit;
	}
}
